﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.Classifieds
{
    public static class Search
    {
        public static Adams.Web.Models.Classifieds.Search.PageLoad PageLoad(string criteria)
        {
            var data = new Adams.Web.Models.Classifieds.Search.PageLoad() {
                Postings = new Shared.Entities.Classifieds.PostingCollection()
            };

            using (SqlDataReader dr = DB.RunDataReader(@"
SELECT P.PostingID,P.CategoryID,P.StatusID,P.Title,P.Price,P.Location,P.ReplyTo,P.Description,P.CreatedOn,P.ExpiresOn,C.Name As CategoryName,T.TypeID AS TypeID, T.Name AS TypeName
FROM Classifieds.Postings P 
INNER JOIN Classifieds.Categories C ON P.CategoryID = C.CategoryID 
INNER JOIN Classifieds.Types T ON C.TypeID = T.TypeID 
WHERE FREETEXT ((Title,Price,Location,Description), '" + criteria.Replace("'", "''") + @"' )
AND P.StatusID =2  AND DATEDIFF(d, GETDATE(), P.ExpiresOn) >= 0
ORDER BY ExpiresOn DESC
", CommandType.Text,
    DB.CreateParameter("@Search", criteria)))
            {
                while (dr.Read())
                {
                    var Posting = DB.InitFromReader<Shared.Entities.Classifieds.Posting>(dr, new ColMap { NameInDb = "PostingID", NameInObject = "ID" });
                    Posting.Status = (Shared.Entities.Classifieds.Status)dr["StatusID"].DbInt();
                    Posting.Category = new Shared.Entities.Classifieds.Category()
                    {
                        ID = dr["CategoryID"].DbInt(),
                        Name = dr["CategoryName"].DbString(),
                        Type = new Shared.Entities.Classifieds.Type()
                        {
                            ID = dr["TypeID"].DbInt(),
                            Name = dr["TypeName"].DbString()
                        }
                    };

                    data.Postings.Add(Posting);
                }
            }

            return data;
        }
    }
}